package top.lingchen.blogapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableLogic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.lingchen.blogapi.bean.SysUser;
import top.lingchen.blogapi.service.LoginService;
import top.lingchen.blogapi.service.SysUserService;
import static top.lingchen.blogapi.vo.ErrorCode.*;

import top.lingchen.blogapi.utils.JWTUtils;
import top.lingchen.blogapi.vo.Result;
import top.lingchen.blogapi.vo.params.LoginParam;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author 凌宸
 * @create 2021-12-16 下午 5:05
 * @Description
 * @Version 1.0
 */
@Service
@Transactional
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String slat = "lingchen!@#";

    @Override
    public Result login(LoginParam loginParam) {
        /**
         * 1.检查参数是否合法
         * 2. 根据用户名和密码去 user 表中查询记录是否存在
         * 3.如果不存在，登录失败
         * 4.如果存在，使用 JWT 生成 token 返回给前端
         * 5. 将 token 放入 redis 中， redis token：user 信息，设置过期时间
         * (登录验证时，先验证 token 字符串是否合法， 去 redis 认证是否存在)
         */
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        if(!StringUtils.hasLength(account) || !StringUtils.hasLength(password)){
            return Result.fail(PARAMS_ERROR.getCode(), PARAMS_ERROR.getMsg());
        }
        password = DigestUtils.md5Hex(password + slat);
        SysUser sysUser = sysUserService.findUser(account, password);
        if(sysUser == null){
            return Result.fail(ACCOUNT_PWD_NOT_EXIST.getCode(), ACCOUNT_PWD_NOT_EXIST.getMsg());
        }

        String token = JWTUtils.createToken(sysUser.getId());
        stringRedisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public Result logout(String token) {
        stringRedisTemplate.delete("TOKEN_" + token);
        return Result.success(null);
    }

    @Override
    public Result register(LoginParam loginParam) {
        /**
         * 1.判断参数是否合法
         * 2.判断账户是否存在，存在，则返回账户已经被注册
         * 3.如果账户不存在，注册用户
         * 4.生成 token
         * 5.存入 redis 并返回
         * 6. 注意加上事务，一旦中间的过程出现问题，注册的用户需要回滚，
         */
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        String nickname = loginParam.getNickname();
        if(!StringUtils.hasLength(account)
                || !StringUtils.hasLength(password)
                || !StringUtils.hasLength(nickname)){
            return Result.fail(PARAMS_ERROR.getCode(), PARAMS_ERROR.getMsg());
        }
        SysUser sysUser = sysUserService.findUserByAccount(account);
        if(sysUser != null){
            return Result.fail(ACCOUNT_EXIST.getCode(), ACCOUNT_EXIST.getMsg());
        }
        sysUser = new SysUser();
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password + slat));
        sysUser.setNickname(nickname);
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1);
        sysUser.setDeleted(0);
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        sysUserService.save(sysUser);

        String token = JWTUtils.createToken(sysUser.getId());
        stringRedisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        return Result.success(token);

    }

    public static void main(String[] args) {
        String password = DigestUtils.md5Hex("lisi" + slat);
        System.out.println(password);
    }
}
